package viewModel;

import java.text.DateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;

import component.Icons;

import domain.Book;
import domain.Copy;
import domain.Library;

import view.tables.IconizedInterface;

public class BookAvailability implements IconizedInterface {
	private static Map<Book, BookAvailability> instances = new HashMap<Book, BookAvailability>();
	private Book book;
	private Library lib;
	DateFormat dateFormat = DateFormat.getDateInstance();

	private BookAvailability(Book book) {
		this.book = book;
		lib = Library.getInstance();
	}
	
	public static BookAvailability getInstanceOf(Book book){
		BookAvailability inst =  instances.get(book);
		if(inst == null){
			inst = new BookAvailability(book);
			instances.put(book, inst);
		}
		return inst;
	}

	@Override
	public Icon getIcon() {
		for (Copy copy : lib.getCopiesOfBook(book)) {
			if (CopyAvailability.getInstanceOf(copy).isAvailable()) {
				return Icons.COPY_AVAILABLE;
			}
		}
		return Icons.COPY_UNAVAILABLE;
	}

	public String toString() {
		int available = 0;
		GregorianCalendar firstReturnDue = null;
		for (Copy copy : lib.getCopiesOfBook(book)) {
			if (CopyAvailability.getInstanceOf(copy).isAvailable()) {
				available++;
			} else {
				if(copy.getCondition().isLendable()){
					if (firstReturnDue == null
							|| firstReturnDue.compareTo(copy.getActiveLoan()
									.getReturnDue()) > 0)
						firstReturnDue = copy.getActiveLoan().getReturnDue();
				}
			}
		}
		if (available == 1)
			return new String(available + " Exemplar");
		else if (available > 1)
			return new String(available + " Exemplare");
		else if (firstReturnDue != null)
			return new String("ab "
					+ dateFormat.format(firstReturnDue.getTime()));
		return "Keine ausleihbare Exemplare";
	}

}
